package com.kittlen.managementSystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kittlen.managementSystem.entity.Student;
import com.kittlen.managementSystem.entity.MySqlLimit;
import com.kittlen.managementSystem.entity.Result;
import com.kittlen.managementSystem.entity.Student;
import com.kittlen.managementSystem.service.IChoiceService;
import com.kittlen.managementSystem.service.IStudentService;
import com.kittlen.managementSystem.utils.Md5;
import com.kittlen.managementSystem.utils.ObjectUtil;
import org.springframework.beans.factory.xml.UtilNamespaceHandler;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.rmi.CORBA.Util;
import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * <p>
 * 学员表 前端控制器
 * </p>
 *
 * @author kittlen
 * @since 2021-01-26
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Resource
    IStudentService iStudentService;

    @Resource
    IChoiceService iChoiceService;
    /**
     * 学员登陆
     * @param userId
     * @param pwd
     * @return
     */
    @RequestMapping("/login")
    public Result login(String userId, String pwd, HttpServletRequest request){
        Result result=new Result();
        Student student=iStudentService.getById(userId);
        if(ObjectUtil.isNoEmpty(student)){
            if(pwd.equals(student.getPwd())){
                student.setPwd("");
                result.setData(student);
                request.getSession().setAttribute("user",student);
                request.getSession().setAttribute("type",1);
                return result;
            }
        }
        result.setCode(result.RESULT_ERROR);
        result.setMsg("账号或密码错误");
        return result;
    }

    /**
     * 学员查询
     * @param student
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("selects")
    public Result selects(Student student, @RequestParam(required = false,defaultValue = "0")int page,
                          @RequestParam(required = false,defaultValue = "0")int limit){
        Result result=new Result();
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNoEmpty(student.getStudentId())){
            queryWrapper.like("student_id", student.getStudentId());
        }
        if(ObjectUtil.isNoEmpty(student.getFullname())){
            queryWrapper.like("fullname", student.getFullname());
        }
        if(ObjectUtil.isNoEmpty(student.getAgender())){
            queryWrapper.like("agender", student.getAgender());
        }
        if(ObjectUtil.isNoEmpty(student.getPhone())){
            queryWrapper.like("phone", student.getPhone());
        }
        if(ObjectUtil.isNoEmpty(student.getEmail())){
            queryWrapper.like("email", student.getEmail());
        }
        if(ObjectUtil.isNoEmpty(student.getStudyType())){
            queryWrapper.eq("study_type", student.getStudyType());
        }
        if(ObjectUtil.isNoEmpty(student.getIsEnd())){
            queryWrapper.eq("is_end", student.getIsEnd());
        }
        if (page!=-1) {
            MySqlLimit mySqlLimit=new MySqlLimit(page,limit);
            queryWrapper.last("LIMIT "+mySqlLimit.getOffset()+","+mySqlLimit.getRows());
        }
        List<Student> list=iStudentService.list(queryWrapper);
        for(int i=0;i<list.size();i++){
            list.get(i).setPwd("");
        }
        result.setData(list);
        queryWrapper.last("");
        result.setCount(iStudentService.count(queryWrapper));
        return result;
    }

    /**
     * 学员添加
     * @param student
     * @return
     */
    @RequestMapping("/insert")
    public Result insert(Student student) throws NoSuchAlgorithmException {
        Result result=new Result();
        student.setPwd(Md5.UseMD5("123456"));
        student.setIsEnd(false);
        try {
            if(iStudentService.save(student)) {
                result.setData(student);
                result.setMsg("学员添加成功");
            }else{
                result.setCode(result.RESULT_ERROR);
                result.setMsg("学员添加失败");
            }
        }catch (DuplicateKeyException e){
            result.setCode(result.RESULT_ERROR);
            result.setMsg("学员添加失败,学员ID重复");
        }finally {
            return result;
        }
    }

    /**
     * 学员添加
     * @param studentsStr
     * @return
     */
    @RequestMapping("/studentImport")
    public Result studentImport(String studentsStr){
        Result result=new Result();
        List<Student> list=new Gson().fromJson(studentsStr,new TypeToken<List<Student>>(){}.getType());
        try {
            int count=iStudentService.batchInsert(list);
            if(count>0) {
                result.setMsg("学员添加成功");
            }else{
                result.setCode(result.RESULT_ERROR);
                result.setMsg("学员添加失败");
            }
        }catch (DuplicateKeyException e){
            String err=e.getCause().toString();
            String errID=err.substring(err.indexOf("Duplicate entry")+15,err.indexOf("for key"));
            result.setCode(result.RESULT_ERROR);
            result.setMsg("学员添加失败,学员ID"+errID+"重复");
        }
        return result;
    }

    /**
     * 学员修改信息及选择教练
     * @param student
     * @param coachId
     * @param choiceId
     * @return
     * @throws Exception
     */
    @RequestMapping("/update")
    public Result update(Student student,@RequestParam(required = false,defaultValue = "")String coachId,@RequestParam(required = false,defaultValue = "")String choiceId) throws Exception {
        Result result=new Result();
        if(ObjectUtil.isNoEmpty(coachId)&&ObjectUtil.isNoEmpty(choiceId)){//已经选过教练
            if(iStudentService.updateByCoach(student, coachId, choiceId)){
                result.setData(student);
                result.setMsg("学员信息修改成功");
            }else{
                result.setCode(result.RESULT_ERROR);
                result.setMsg("学员信息修改失败");
            }
        }else if(ObjectUtil.isNoEmpty(coachId)&&!ObjectUtil.isNoEmpty(choiceId)) {//还未选过教练
            if(iStudentService.updateAndSaveChoice(student, coachId)){
                result.setData(student);
                result.setMsg("学员信息修改并分配教练成功");
            }else{
                result.setCode(result.RESULT_ERROR);
                result.setMsg("学员信息修改失败,该教练已经分配到达上限了");
            }
        }else{
            if(iStudentService.updateById(student)){
                result.setData(student);
                result.setMsg("学员信息修改成功");
            }else{
                result.setCode(result.RESULT_ERROR);
                result.setMsg("学员信息修改失败");
            }
        }
        return result;
    }

    /**
     * 修改密码
     * @param
     * @return
     */
    @RequestMapping("/updatePwd")
    public Result updatePwd(String studentId,@RequestParam(required = false,defaultValue = "")String newPwd,@RequestParam(required = false,defaultValue = "")String oldPwd){
        Result result=new Result();
        if(ObjectUtil.isNoEmpty(newPwd)&&ObjectUtil.isNoEmpty(oldPwd)){
            Student student=iStudentService.getById(studentId);
            if(ObjectUtil.isNoEmpty(student)){
                if(student.getPwd().equals(oldPwd)){
                    iStudentService.update(new UpdateWrapper<Student>().set("pwd",newPwd).eq("student_id",studentId));
                    result.setMsg("密码修改成功,请重新登陆");
                }else{
                    result.setMsg("密码修改失败,原密码错误");
                    result.setCode(result.RESULT_ERROR);
                }
            }else{
                result.setMsg("账号信息异常,请重新登陆");
                result.setCode(result.RESULT_ERROR);
            }
        }else{
            try {
                Student student=new Student(studentId);
                student.setPwd(Md5.UseMD5("123456"));
                iStudentService.updateById(student);
                result.setMsg("密码重置成功");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 开始选择教练
     * @param
     * @return
     */
    @RequestMapping("/updates")
    public Result updates(int type){
        Result result=new Result();
        UpdateWrapper<Student> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("study_type",1).eq("study_status",type-1).set("study_type",-1).set("study_status",type);
        iStudentService.update(updateWrapper);
        return result;
    }

    /**
     * 修改学员毕业情况
     * @param
     * @return
     */
    @RequestMapping("/updatesByIsEnd")
    public Result updatesByIsEnd(String studentsStr,int isEnd){
        Result result=new Result();
        Student.Students students=new Gson().fromJson(studentsStr,Student.Students.class);
        UpdateWrapper<Student> updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("is_end",isEnd).in("student_id",students.getStudentIds());
        iStudentService.update(updateWrapper);
        return result;
    }

    /**
     * 学员删除
     * @param student
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Student student){
        Result result=new Result();
        if(iStudentService.removeById(student)) {
            result.setMsg("删除成功");
        }else{
            result.setMsg("删除失败");
            result.setCode(result.RESULT_ERROR);
        }
        return result;
    }
}
